import re
import json
from datetime import datetime
from utils.ssh import SSH2

now = datetime.now()

year = now.strftime("%Y")
abd_date = now.strftime("%a %b %d")
ymd_date = now.strftime("%y-%m-%d")
ymd_date_1 = now.strftime("%y/%m/%d")
ymd_date_2 = now.strftime("%y.%m.%d")

date_now = now.strftime("%Y-%m-%d %H:%M:%S")

pattern = rf"{abd_date}[\s\S]+{year}|{ymd_date}|{ymd_date_1}|{ymd_date_2}"


def main(hosts, params):
    results = []
    detail = f"{now.strftime('%Y-%m-%d %H:%M:%S')}\n"
    params_obj = json.loads(params)
    logs = params_obj.get("logs")
    for host in hosts:
        with SSH2(
            host=host.host, username=host.username, password=host.password
        ) as ssh:
            detail = detail + f"当前设备：{str(host)}\n"
            for log in logs:
                command = log.get("command")
                if command:
                    result = ssh.cmd(command)
                    if result:
                        stdout = result.stdout
                        new_message = f"{command}:\n{stdout}\n"
                        detail = detail + new_message
                        match_obj = re.search(pattern, stdout, re.I | re.S)
                        if match_obj:
                            results.append(
                                {
                                    "host": host,
                                    "title": log.get("title"),
                                    "message": new_message,
                                }
                            )

    return results, detail
